from flask import Blueprint,flash,request,redirect,url_for,render_template
from flask import abort
from Applications.forms.login import LoginForm, RegForm
from ..until import login_manager,load_user,load_user
from flask_login import login_required,login_user,logout_user
from ..model.user import User
bp = Blueprint("user", __name__)


@bp.route("/")
@bp.route('/index.do')
@login_required
def index():
    return "只有登陆用户能看到我"


@bp.route('/reg.do', methods=["GET", "POST"])
def reg():
    Form = RegForm()
    return render_template("login.html", form=Form)


@bp.route('/login.do', methods=["GET", "POST"])
def login():
    # Here we use a class of some kind to represent and validate our
    # client-side form data. For example, WTForms is a library that will
    # handle this for us, and we use a custom LoginForm to validate.
    form = LoginForm()
    if form.validate_on_submit():
        # Login and validate the user.
        # user should be an instance of your `User` class
        login_user(user)

        flash('Logged in successfully.')

        next = request.args.get('next')
        # next_is_valid should check if the user has valid
        # permission to access the `next` url
        if not form.next_is_valid(next):
            return abort(400)

        return redirect(next or url_for('index'))
    return render_template('login.html', form=form)


@bp.route('/logout.do')
def logout():
    logout_user()
    return redirect(url_for("user.index"))


@bp.route('/user.do/<int:user_id>')
def user(user_id):
    return "user reg"
